<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加与搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <template #append>
              <el-button icon="el-icon-search" @click="getUserList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table class="tableMagHgt" :data="userList" style="width: 100%" stripe border >
        <el-table-column type="index" label="序列" width="50px"></el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="role_name" label="权限">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column label="状态">
          <!-- 直接展示获取到的不是该行的数据而是一个值 -->
          <!-- <el-switch v-model="mg_state" inactive-text="直接展示"></el-switch> -->
          <template v-slot="scopes">
            <el-switch v-model="scopes.row.mg_state" :active-text="scopes.row.mg_state?'开启': '关闭'" @change="userStateChenged(scopes.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="space">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDiolog(space.row.id)"></el-button>
            <!-- 分配 -->
            <el-tooltip class="item" effect="dark" content="分配权限" :enterable="false" placement="top">
               <el-button type="warning" icon="el-icon-share" size="mini" @click="setRole(space.row)"></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUserById(space.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 弹出层-添加用户界面 -->
    <el-dialog
      title="添加用户"
      v-model="dialogVisible"
      width="50%" @closed="addDialogClosed">
      <!-- 内容主题 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <!-- 账户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 弹出层-修改用户数据界面 -->
    <el-dialog
      title="添加用户"
      v-model="editDiologVisibles"
      width="50%" @closed="editDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <!-- 账户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDiologVisibles = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      v-model="setRoleDialogVisible"
      width="50%"
      @close="setRoleDiologClose">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleName" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) {
        callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      // 返回参数
      userList: [],
      // 总记录数
      total: 0,
      // 弹出层的显示与隐藏-添加用户界面
      dialogVisible: false,
      // 添加用户的表单数据  内容主题-model
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单的验证规则对象 内容主题-rules
      addFormRules: {
        username: [
          // 必填项
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // 长度校验规则
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          // 必填项
          { required: true, message: '请输入密码', trigger: 'blur' },
          // 长度校验规则
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          // 必填项
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          // 必填项
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 弹出层的显示与隐藏-修改用户数据界面
      editDiologVisibles: false,
      // 存放获取的单项用户数据
      editForm: {},
      // 添加表单的验证规则对象 - 修改用户数据界面
      editFormRules: {
        email: [
          // 必填项
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          // 必填项
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 保存用户数据
      userInfo: {},
      // 保存获取所有角色的数据列表
      rolesList: [],
      // 保存已选中的值
      selectedRoleName: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户数据
    async getUserList() {
      const { data: res } = await this.$axios.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败！')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 修改用户状态，根据switch的状态触发下方函数
    async userStateChenged(intoChengde) {
      const { data: res } = await this.$axios.put(`users/${intoChengde.id}/state/${intoChengde.mg_state}`)
      // console.log(intoChengde.id)
      if (res.meta.status !== 200) {
        intoChengde.mg_state = !intoChengde.mg_state
        return this.$message.error('修改用户状态失败！')
      }
      this.$message.success('修改用户状态成功！')
    },
    // 监听弹出层的关闭 -添加用户界面
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定上传数据
    addUser() {
      // 效验数据
      this.$refs.addFormRef.validate(async (valid, obj) => {
        console.log(valid, obj)
        if (valid !== true) return
        // 发起请求
        const { data: res } = await this.$axios.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('提交用户数据失败')
        this.$message.success('提交用户数据成功')
        // 关闭弹出层
        this.dialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 展示修改用户数据界面的对话框
    async showEditDiolog(id) {
      const { data: res } = await this.$axios.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败')
      this.editForm = res.data
      this.editDiologVisibles = true
    },
    // 修改用户数据界面确定按钮
    editUser() {
      // 对表单预验证
      this.$refs.editFormRef.validate(async (valid, obj) => {
        if (!valid) return
        const { data: res } = await this.$axios.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('更新用户信息失败')
        this.$message.success('更新用户信息成功')
        // 关闭弹出层
        this.editDiologVisibles = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 监听弹出层的关闭 -修改用户数据界面
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 根据ID删除用户信息
    async delUserById(id) {
      const info = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      // console.log(info)
      // 确认删除，返回字符串 confirm
      // 取消删除，返回字符串 cancel
      if (info !== 'confirm') return this.$message.info('取消用户信息删除成功')
      const { data: res } = await this.$axios.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户信息失败')
      this.$message.success('删除用户信息成功')
      // 刷新用户列表
      this.getUserList()
    },
    // 点击展示分配对话框的隐藏
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前，获取所有的角色列表
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      // console.log(this.rolesList)
      // 打开展示分配对话框
      this.setRoleDialogVisible = true
    },
    // 点击保存角色信息并上传
    async saveRoleInfo() {
      if (!this.selectedRoleName) {
        return this.$message.error('未选则权限！')
      }
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleName })
      if (res.meta.status !== 200) {
        this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框关闭事件
    setRoleDiologClose() {
      this.selectedRoleName = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.tableMagHgt {
  margin-top: 15px;
  font-size: 14px;
}
</style>
